/*
 * Copyright 2013 Glassy Cinema.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package hu.glassy.web.util;

import hu.glassy.core.model.Account;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.util.Assert;

/**
 * A jelszó titkosítását végzi.
 *
 * @author molnar.alexander@sonrisa.hu
 */
public class PasswordHelper
{

  /**
   * Titkosítja a paraméterben kapott jelszót, és visszatér a titkosított
   * értékkel.
   *
   * @param password
   *
   * @return
   */
  public static String encrypt(final String password)
  {
    Assert.hasLength(password);

    try
    {
      final MessageDigest md5Digest = MessageDigest.getInstance("MD5");
      md5Digest.update(password.getBytes("UTF-8"));
      final byte[] digest = md5Digest.digest();
      final BigInteger bigInt = new BigInteger(1, digest);
      String encryptedString = bigInt.toString(16);

      if (encryptedString.length() > Account.PASSWORD_LENGTH)
      {
        return encryptedString.substring(0, Account.PASSWORD_LENGTH);

      }
      else
      {
        while (encryptedString.length() < Account.PASSWORD_LENGTH)
        {
          encryptedString = "0" + encryptedString;
        }

        return encryptedString;
      }

    }
    catch (final NoSuchAlgorithmException e)
    {
      throw new IllegalStateException(e);
    }
    catch (final UnsupportedEncodingException e)
    {
      throw new IllegalStateException(e);
    }
  }

  /**
   * Generál egy új, véletlen karakterekből álló jelszót
   *
   * @param count
   *              A jelszó hossza
   *
   * @return
   */
  public static String generateRandomPassword(final int count)
  {
    return RandomStringUtils.randomAlphanumeric(count);
  }
}
